<?php
namespace App\Admin\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Route;
use Illuminate\Validation\Rule;
use App\Admin\Models\Role;

class SystemRoleRequest extends FormRequest
{

    private $roleModel;

    public function rules(): array
    {
        if( $this->isUpdate() ){
            return $this->updateRules();
        }

        return [
            'name'     => ['required', 'alpha_num', 'between:2,50', 'unique:system_role'],
            'code'     => ['required', 'alpha_num:ascii', 'between:2,50', 'unique:system_role'],
            'sort'     => 'required|integer|between:0,1000000',
            'status'   => 'required|integer|boolean',
        ];
    }

    public function updateRules(): array
    {
        $unique = Rule::unique('system_role')->ignore($this->getRoleModel());

        return [
            'name'     => ['sometimes', 'alpha_num', 'between:2,50', $unique],
            'code'     => ['sometimes', 'alpha_num:ascii', 'between:2,50', $unique],
            'sort'     => 'sometimes|integer|min:0',
            'status'   => 'sometimes|integer|accepted_if:id,1',
        ]; 
    }

    public function attributes()
    {
        return [
            'name'   => '角色名称',
            'code'   => '角色代码',
            'sort'   => '排序',
            'status' => '角色状态',
        ];
    }

    public function messages()
    {
        return [
            'name' => '角色名限制长度2-50, 禁止特殊字符',
            'name.unique' => '角色名已存在',
            'code' => '角色代码限制长度2-50, 只能为字母和数字',
            'code.unique' => '角色代码已存在',

            'status'   => '[超级管理员]角色具有特殊性，不可禁用或删除',
        ];
    }

    private function isUpdate()
    {
        return $this->isMethod('PUT');
        return Route::currentRouteAction() == '\App\Admin\Controllers\System\RoleController@update';
    }

    public function getRoleModel()
    {
        if( !$this->roleModel ){
            $role_id = $this->route('id');
            $this->roleModel = Role::where('id', $role_id)->first();
            abort_if(!$this->roleModel, 422, "要修改的角色不存在{$role_id}");
        }

        return $this->roleModel;
    }


    public function updateRole()
    {
        return $this->getRoleModel()->update( $this->validated() );
    }


    public function createRole()
    {
        return Role::create( $this->validated() );
    }
}
